import React, { Component } from 'react'
import store from '../../../redux'
import Api from '../../../config/api'
import axios from 'axios'
import Com from '../../../common/common'

import Navbar from '../../../Component/navbar'

import Button from 'antd/lib/button'
import Table from 'antd/lib/table'
import Spin from 'antd/lib/spin'
import Icon from 'antd/lib/icon'
import Input from 'antd/lib/input'
import DatePicker from 'antd/lib/date-picker'
import Form from 'antd/lib/form'
import message from 'antd/lib/message'
import Modal from 'antd/lib/modal'
import Tree from 'antd/lib/tree'

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const antIcon = <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />;
const FormItem = Form.Item;
const confirm = Modal.confirm;
const { TextArea } = Input;
const TreeNode = Tree.TreeNode;

let oper = null;

const refreshAuth = () => {
    axios.post(Api['refreshAuth']);
}

class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: '',
            endDate: '',
            startMonent: null,
            endMoment: null,
            authTree: [],
            showAddModal: false
        }
    }
    componentDidMount() {
        this.getSelect();
    }
    getSelect() {
        axios.post(Api['authTree']).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                this.setState({
                    authTree: data
                }, () => { this.search(); this.props.setChannel(this.state.authTree) })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    getTime(type, moment, time) {
        if (type === 'start') {
            this.setState({
                startDate: time,
                startMoment: moment
            })
        }
        else {
            this.setState({
                endDate: time,
                endMoment: moment
            })
        }
    }
    disabledstartTime(current) {
        if (this.state.endMoment) {
            return current > this.state.endMoment
        }
        else {
            return false
        }
    }
    disabledendTime(current) {
        if (this.state.startMoment) {
            return current < this.state.startMoment
        }
        else {
            return false
        }
    }
    search() {
        let obj = {
            name: this.nameInput.input.value,
            startTime: this.state.startDate,
            endTime: this.state.endDate
        }
        this.props.search(obj, this.state.simSelectData, this.state.statusSelectData)
    }
    showAddModal() {
        this.setState({
            showAddModal: true
        })
    }
    handleCancel() {
        this.setState({
            showAddModal: false
        })
    }
    handleSure(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                axios.post(Api['addRole'], data).then(res => {
                    if (res) {
                        this.search();
                        this.props.form.resetFields()
                        refreshAuth()
                        message.success('提交成功')
                        this.setState({
                            showAddModal: false
                        })
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            }
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        return (
            <Navbar ref={(item) => {oper=item}} className="account-operbar">
                <Form layout="inline">
                    <FormItem label="角色名称"><Input style={{ width: '150px' }} ref={(input) => { this.nameInput = input }} /></FormItem>
                    <FormItem label="开始时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledstartTime.bind(this)} onChange={this.getTime.bind(this, 'start')} />
                    </FormItem>
                    <FormItem label="结束时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledendTime.bind(this)} onChange={this.getTime.bind(this, 'end')} />
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="search" onClick={this.search.bind(this)}>查询</Button>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="plus" onClick={this.showAddModal.bind(this)}>添加</Button>
                    </FormItem>
                </Form>
                <Modal visible={this.state.showAddModal} onCancel={this.handleCancel.bind(this)} wrapClassName="vertical-center-modal" title="新增" footer={[
                    <Button key="sure" type="primary" onClick={this.handleSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.handleCancel.bind(this)}>取消</Button>
                ]} >
                    <Form className="add-account-form">
                        <FormItem label="角色名称" {...formItemLayout}>
                            {getFieldDecorator('name', { validateFirst: true, rules: [{ required: true, message: '请输入角色名' }, { max: 10, message: '10位以内' },Com.validateSpace] })(<Input />)}
                        </FormItem>
                        <FormItem label="角色描述" {...formItemLayout}>
                            {getFieldDecorator('description', { validateFirst: true, rules: [{ max: 500, message: '500位以内' }] })(<TextArea row={3} />)}
                        </FormItem>
                    </Form>
                </Modal>
            </Navbar>
        )
    }
}

const ValidateOperbar = Form.create()(OperBar);

class Table1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataNum: 0,
            tableHeight: 300,
            tableData: this.props.tableData,
            showEditModal: false,
            authTree: [],
            checkedKeys: [],
            autoExpandParent: true,
            nowRowId: 0,
            showTreeModal: false,
            nowTreeRow: [],
            currentPage: 1
        }
    }
    componentWillMount() {
        this.setState({
            authTree: this.props.channelData
        })
    }
    componentDidMount() {
        setTimeout(() => {
            let operbarHeight = oper.box.offsetHeight + 10 + 10;
            this.setState({
                tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
            })
            this.unscribe = store.subscribe(this.fullTable.bind(this))
        }, 100)
    }
    componentWillReceiveProps(nextprops) {
        this.setState({
            tableData: nextprops.tableData,
            dataNum: nextprops.dataNum,
            authTree: nextprops.channelData,
            currntPage: nextprops.currentPage,
        })
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullTable() {
        let operbarHeight = oper.box.offsetHeight + 10 + 10;
        this.setState({
            tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
        })
    }
    editModalShow(record) {
        this.setState({
            showEditModal: true,
            nowRowId: record.id
        })
        this.props.form.setFieldsInitialValue({
            name: record.name,
            description: record.description
        })
    }
    editCancel() {
        this.setState({
            showEditModal: false
        })
    }
    editSure(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                data.id = this.state.nowRowId;
                axios.post(Api['editRole'], data).then(res => {
                    if (res) {
                        this.props.search();
                        this.props.form.resetFields()
                        refreshAuth()
                        message.success('提交成功')
                        this.setState({
                            showEditModal: false
                        })
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            }
        });
    }
    deleteRow(record) {
        this.props.deleteRow(record)
    }
    validatePassword(rule, value, callback) {
        if (value === this.props.form.getFieldsValue(['password']).password) {
            callback()
        }
        else {
            callback('两次密码输入不一致')
        }
    }
    onCheck(checkedKeys) {
        this.setState({ checkedKeys });
    }
    renderTreeNodes(data) {
        return data.map((item) => {
            if (item.children && item.children.length) {
                return (
                    <TreeNode title={item.name} key={item.code} dataRef={item} >
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode key={item.code} title={item.name} />;
        });
    }
    treeModalShow(record) {
        let keys = [];
        if (record.permissionCodes) {
            keys = record.permissionCodes.split(',')
        }
        this.setState({
            checkedKeys: keys
        }, () => {
            this.setState({
                showTreeModal: true,
                nowTreeRow: record
            })
        })
    }
    treeModalCancel() {
        this.setState({
            showTreeModal: false
        })
    }
    treeSure(e) {
        e.preventDefault();
        let id = this.state.nowTreeRow.id;
        let permissionCodes = this.state.checkedKeys.join(',');
        axios.post(Api['modAuth'],{id,permissionCodes}).then(res => {
            if (res) {
                this.props.search();
                message.success('提交成功')
                refreshAuth()
                this.setState({
                    showTreeModal: false
                })
            }
        }).catch(function (error) {
            console.log(error)
        })
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        const columns = [
            // { title: 'ID', dataIndex: 'id', key: '1', width: '10%' },
            { title: '角色名称', dataIndex: 'name', key: '2', width: '25%' },
            { title: '角色描述', dataIndex: 'description', key: '3', width: '25%' },
            { title: '创建时间', dataIndex: 'createTime', key: '4', width: '20%' },
            {
                title: '操作',
                key: '5',
                width: '30%',
                render: (record) => {
                    return (
                        <div>
                            <a onClick={this.treeModalShow.bind(this, record)}>分配权限</a>
                            <a onClick={this.editModalShow.bind(this, record)} style={{ marginLeft: '10px ' }}>编辑</a>
                            <a onClick={this.deleteRow.bind(this, record)} style={{ marginLeft: '10px ' }}>删除</a>
                        </div>
                    )
                }
            },
        ];
        return (
            <div className="account-table" style={{ marginTop: '10px' }}>
                <Table title={(data) => { return '角色列表' }} columns={columns} dataSource={this.state.tableData} pagination={{
                    onChange: this.props.changePage,
                    onShowSizeChange: this.props.changePageSize,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100'],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    current: this.state.currntPage,
                    total: this.state.dataNum,
                    showTotal: total => `共 ${total} 条数据`
                }} scroll={{ y: this.state.tableHeight }}></Table>
                <Modal visible={this.state.showEditModal} onCancel={this.editCancel.bind(this)} wrapClassName="vertical-center-modal" title="配置" footer={[
                    <Button key="sure" type="primary" onClick={this.editSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.editCancel.bind(this)}>取消</Button>
                ]} >
                    <Form className="add-account-form">
                        <FormItem label="角色名称" {...formItemLayout}>
                            {getFieldDecorator('name', { validateFirst: true, rules: [{ required: true, message: '请输入角色名' }, { max: 10, message: '10位以内' },Com.validateSpace] })(<Input />)}
                        </FormItem>
                        <FormItem label="角色描述" {...formItemLayout}>
                            {getFieldDecorator('description', { validateFirst: true, rules: [{ max: 500, message: '500位以内' }] })(<TextArea row={3} />)}
                        </FormItem>
                    </Form>
                </Modal>
                <Modal visible={this.state.showTreeModal} onCancel={this.treeModalCancel.bind(this)} wrapClassName="vertical-center-modal" title="分配权限" footer={[
                    <Button key="sure" type="primary" onClick={this.treeSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.treeModalCancel.bind(this)}>取消</Button>
                ]} >
                    <Tree
                        checkable
                        autoExpandParent={this.state.autoExpandParent}
                        onCheck={this.onCheck.bind(this)}
                        checkedKeys={this.state.checkedKeys}
                    >
                        {this.renderTreeNodes(this.state.authTree)}
                    </Tree>
                </Modal>
            </div >
        )
    }
}

const ValidateTable = Form.create()(Table1);

class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            totalNum: 0,
            tableData: [],
            searchParams: {},
            paginationData: {
                current: 1,
                pageNum: 1,
                pageSize: 20
            },
            authTree: [],
            loading: true,
            currentPage: 1,
        }
    }
    setParams(obj) {
        let data = JSON.parse(JSON.stringify(obj));
        this.setState({
            searchParams: data
        }, () => {
            this.search('btn');
        })
    }
    setChannel(data) {
        this.setState({
            authTree: data,
        })
    }
    search(type) {
        let data = JSON.parse(JSON.stringify(this.state.searchParams));
        if (type === 'btn') {
            data.pageNum = 1;
            this.setState({
                currentPage: 1
            })
        } else {
            data.pageNum = this.state.paginationData.pageNum;
        }
        data.pageSize = this.state.paginationData.pageSize;
        this.setState({
            loading: true,
        })
        axios.post(Api['getRolesByParams'], data).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                data.list.forEach((item, index) => {
                    item.key = index;
                })
                this.setState({
                    loading: false,
                    tableData: data.list,
                    totalNum: data.total
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    changePageSize(current, size) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = current;
        pagination.pageSize = size;
        this.setState({
            paginationData: pagination,
            currentPage: current
        }, () => { this.search('pag') })
    }
    changePage(pageNum, pageSize) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = pageNum;
        pagination.pageSize = pageSize;
        this.setState({
            paginationData: pagination,
            currentPage: pageNum
        }, () => { this.search('pag') })
    }
    deleteRow(record) {
        let that = this;
        confirm({
            title: '删除',
            content: '您确定要删除' + record.name + '吗？',
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                axios.post(Api['deleteRole'] + '?id=' + record.id).then(res => {
                    if (res) {
                        that.search();
                        message.success('删除成功')
                        refreshAuth()
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            },
            onCancel() { },
        });
    }
    render() {
        return (
            <div>
                <ValidateOperbar search={this.setParams.bind(this)} setChannel={this.setChannel.bind(this)} />
                <Spin spinning={this.state.loading} indicator={antIcon}>
                    <ValidateTable
                        search={this.search.bind(this)}
                        tableData={this.state.tableData}
                        dataNum={this.state.totalNum}
                        currentPage={this.state.currentPage}
                        changePageSize={this.changePageSize.bind(this)}
                        changePage={this.changePage.bind(this)}
                        deleteRow={this.deleteRow.bind(this)}
                        channelData={this.state.authTree}
                    />
                </Spin>
            </div>
        )
    }
}

export default Box